<template>
	<view class="app-container">
		<!-- 登錄 -->
		<authorize @onLoadFun="onLoadFun" isGoIndex></authorize>
		<view class="cu-card">
			<mescroll-body ref="mescrollUni" @init="mescrollInit" class="app-mescroll" :up="upOption" :down="downOption" @down="downCallback" @up="upCallback">
				<view class="card cu-item padding-0 shadow cu-list menu" v-for="(item, index) in list" :index="index" :key="index">
					<view class="cu-item padding-right-0">
						<view class="order-id">
							<text class="text-grey">订单编号 {{ item.order_number }}</text>
						</view>
						<view class="cu-tag bg-primary text-white">{{ item.status | filterStatus }}</view>
					</view>
					<view class="cu-item content flex-direction text-grey">
						<view v-for="(type, index) in orderItems" :key="index" class="order-item desc margin-tb-xs">{{ type.name }}：{{ item[type.key] || '暂无' }}</view>
					</view>
					<view class="cu-item padding-0 justify-end">
						<button v-if="item.status === 2 || item.status === 0" class="cu-btn line-primary text-primary shadow sm margin-right" @tap="cancelEvent(item)">
							取消预约
						</button>
						<button class="cu-btn line-primary text-primary shadow sm margin-right" v-if="item.status === 0" @tap="payMethod(item)">支付</button>
						<button class="cu-btn line-primary text-primary shadow sm margin-right" v-if="item.status === 6" @tap="feedbackEvent(item)">申请退款</button>
					</view>
				</view>
			</mescroll-body>
		</view>
		<PaymentModal ref="PaymentModal" title="校验安全密码" v-model="payFlag" @confirm="confirmPassword"></PaymentModal>
	</view>
</template>

<script>
import { PAGE_SIZE } from '@/common/tools/config.js';
import { getCloudPrintHistoryOrderList, changeNoPrintOrderStatus } from '@/api/order.js';
import { paymentInterface } from '../api/pay';
import PaymentModal from '@/components/payment-modal/password.vue';
import MescrollBody from '@/components/mescroll-uni/mescroll-body.vue';
import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';
import authorize from '@/components/authorize/authorize.vue';

export default {
	mixins: [MescrollMixin],
	components: {
		MescrollBody,
		PaymentModal,
		authorize
	},
	data() {
		return {
			downOption: {
				auto: false, //是否在初始化后,自动执行下拉回调callback; 默认true
				native: true // 启用系统自带的下拉组件,默认false;仅mescroll-body生效,mescroll-uni无效
			},
			upOption: {
				use: true, // 是否启用上拉加载; 默认true
				auto: false, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true,
				empty: {
					icon: "/static/img/noOrder.png"
				}
			},
			payFlag: false,
			orderItems: [
				{
					name: '订单时间',
					key: 'create_time'
				},
				{
					name: '所在区域',
					key: 'area_name'
				},
				{
					name: '打印内容',
					key: 'cloud_print_type_name'
				},
				{
					name: '打印份数',
					key: 'copies'
				},
				{
					name: '提取码',
					key: 'code'
				},
				{
					name: '商品总额',
					key: 'price'
				},
				{
					name: '实付款',
					key: 'actual_price'
				}
			],
			list: [],
			paymentMethods: null,
			//选择当前
			row: {}
		};
	},
	filters: {
		filterStatus(value) {
			const orderStates = {
				0: '未支付',
				1: '已取消',
				2: '未打印',
				3: '退款中',
				4: '已退款',
				5: '售后中',
				6: '已完成',
				7: '已提交需求'
			};
			return orderStates[value];
		}
	},
	methods: {
		onLoadFun() {
			this.mescroll.resetUpScroll();
		},
		/**
		 * 下拉刷新的回调
		 * @param {Object} mescroll
		 */
		downCallback(mescroll) {
			mescroll.resetUpScroll();
		},
		/**
		 * 上拉加载的回调
		 * @param {num} 页码, 默认从1开始
		 * @param {size} 页长, 默认每页10条
		 */
		upCallback(mescroll) {
			const { num, size } = mescroll;
			this.getCloudPrintHistoryOrderListEvent({
				status: [0,1,2,3,4,5,6,7],
				pageSize: size,
				currentPage: num
			})
				.then(result => {
					if (num == 1) this.list = [];
					this.list = this.list.concat(result.showing);
					mescroll.endBySize(result.showing.length, result.total);
				})
				.catch(err => {
					// 失败隐藏下拉加载状态
					mescroll.endErr();
				});
		},
		/**
		 * 查询云打印历史订单列表
		 */
		getCloudPrintHistoryOrderListEvent(item) {
			return new Promise((resolve, reject) => {
				getCloudPrintHistoryOrderList(item).then(res => {
					resolve(res.result);
				});
			}).catch(err => {
				reject(err);
			});
		},
		/**
		 * 选择支付方式
		 */
		payMethod(item) {
			this.row = item;
			if (this.row.payment_type == 1) {
				uni.showActionSheet({
					itemList: ['余额支付'],
					success: res => {
						this.paymentMethod = 1;
						this.balancePay();
					}
				});
			} else if (this.row.payment_type == 2) {
				uni.showActionSheet({
					itemList: ['微信支付'],
					success: res => {
						this.paymentMethod = 2;
						this.wechatPay(0);
					}
				});
			}
		},
		/**
		 * 微信支付
		 */
		wechatPay(e) {
			// 微信支付封印
			if (e === 0) {
				uni.showToast({
					icon: 'none',
					title: '微信支付请在所收到的客服支付消息中完成'
				});
				return;
			}
			//有订单号时
			//第一步: 获取支付参数
			this.paymentInterfaceEvent().then(result => {
				//第二步：发起微信支付
				this.payEvent(result);
			});
		},
		/**
		 * 调起微信支付
		 * @param result
		 */
		payEvent(result) {
			const { nonceStr, paySign, signType, timeStamp } = result;
			wx.requestPayment({
				nonceStr: nonceStr,
				package: result.package,
				paySign: paySign,
				signType: signType,
				timeStamp: timeStamp.toString(),
				success: res => {
					if (res.errMsg === 'requestPayment:ok') {
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 6000
						});
						this.$refs.mescrollUni.mescroll.resetUpScroll();
					}
				},
				fail: res => {
					if (res.errMsg !== 'requestPayment:fail cancel') {
						uni.showModal({
							title: '支付错误',
							content: '可能遇到网络堵塞，建议重新尝试提交预约'
						});
					}
				}
			});
		},
		/**
		 * 余额支付
		 */
		balancePay() {
			//验证密码
			this.payFlag = true;
		},
		/**
		 * 输入密码后确认事件
		 * @param {Object} value 密码
		 */
		confirmPassword(value) {
			//支付
			this.paymentInterfaceEvent(value).then(res => {
				uni.showToast({
					title: '支付成功',
					icon: 'success',
					duration: 6000
				});
				this.$refs.mescrollUni.mescroll.resetUpScroll();
				this.$refs.PaymentModal.hideModal();
			});
		},
		/**
		 *  获取支付流水号
		 */
		paymentInterfaceEvent(password) {
			return new Promise(resolve => {
				const row = this.row;
				paymentInterface({
					payType: this.paymentMethod,
					body: row.cloud_print_type_name,
					out_trade_no: row.order_number,
					order_id: row.print_order_id || '',
					payment_code: password || '',
					orderType: 1
				}).then(res => {
					resolve(res.result);
				});
			});
		},
		/**
		 * 取消预约
		 * @param {Object} row 选择的内容
		 */
		cancelEvent(row) {
			changeNoPrintOrderStatus({
				print_order_id: row.print_order_id,
				type: row.status === 0 ? 1 : 2
			}).then(res => {
				uni.showToast({
					title: '取消预约成功, 提取码失效',
					icon: 'success',
					duration: 6000
				});
				this.$refs.mescrollUni.mescroll.resetUpScroll();
			});
		},
		/**
		 * 反馈
		 */
		feedbackEvent(item) {
			uni.navigateTo({
				url: '/user-pages/feedbackDetail?type=2&orderId=' + item.print_order_id
			});
		},
	}
};
</script>

<style lang="scss">
page {
	background-color: #f1f1f1 !important;
}

.order-item {
	display: block;
	width: 100%;
}
.padding-0 {
	padding: 0 !important;
}
</style>
